<?php

@session_start();

class Cart extends Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        // echo 'in';exit;
		

        unset($_SESSION['view_message']);
        $sql = new sql();
        $sql->connect();
        $this->view->category = $sql->fetchAll("tbl_category", array("1" => '1'));
        $this->view->successMessage = "";
        $this->view->ErrorMessage = "";
        $coupon_code = '';
        $coupon_price = 0;
        $coupon_category = '';
        $coupon_product = '';
        $coupon_type = '';
        $coupon_apply = '';
        //$coupon_status ='valid';


        $invalid_coupon_code = 'no';
        $ErrorArray = array();
        $total_Amount = '';
        //$this->view->quantity_numb = "";	 
        if (isset($_POST['remove_coupon_code'])) {
            unset($_SESSION['coupon_detail']);
        }


        if (isset($_POST['go_coupon_code'])) {

            $coupon_code = $_POST['coupon_code'];
			
			if($coupon_code != '') {
				$lastcouponquery = "select * from tbl_coupon where cp_code ='" . $coupon_code . "' and cp_status = 1 and  cp_startdate <= '" . date('Y-m-d') . "'";
				$lastCoupon = $sql->SimpleQuery($lastcouponquery);
				$coupon_price = '';
				if (count($lastCoupon) > 0) {
					$coupon_price = $lastCoupon[0]['cp_price'];
					//if never expiry not checked
					if ($lastCoupon[0]['cp_expirystatus'] != 1) {
						if ($lastCoupon[0]['cp_startdate'] <= date('Y-m-d') && $lastCoupon[0]['cp_expiry_date'] >= date('Y-m-d')) {
							if ($lastCoupon[0]['no_limit_used'] != 1) {
								if ($lastCoupon[0]['cp_used_time'] <= $lastCoupon[0]['cp_used_count']) {
									$ErrorArray[] = 'Invalid coupon code';
								} else {
									foreach ($_SESSION['shoping_cart'] as $key => $prd_value) {
										$total_Amount += $prd_value['prd_qty'] * $prd_value['prd_price'];
									}
        								if ($total_Amount < $lastCoupon[0]['cp_price']) {
										$ErrorArray[] = "The discount amount can't be greater than the subtotal.";
									} else {
										$coupon_code = $lastCoupon[0]['cp_code'];
										$coupon_price = $lastCoupon[0]['cp_price'];

										//check for all order
										if ($lastCoupon[0]['cp_type'] == 'all_order') {
											$coupon_type = 'All order';
											$coupon_apply = '';
										}

										//check for orders over
										if ($lastCoupon[0]['cp_type'] == 'orders_over') {
											// echo $total_Amount."=-==".$lastCoupon[0]['cp_order_price'];

											if ($total_Amount <= $lastCoupon[0]['cp_order_price']) {
												$ErrorArray[] = 'Coupon code only valid for price over '.$lastCoupon[0]['cp_order_price'];
											} else {
												$coupon_type = 'Order Over';
												$coupon_apply = '';
											}
										}

										//check for collection 
										if ($lastCoupon[0]['cp_type'] == 'collection') {
											$count = 0;
											$coupon_type = 'collection';
											$coupon_category = $lastCoupon[0]['cp_cat_id'];
											foreach ($_SESSION['shoping_cart'] as $col_key => $col_value) {
	//                                                echo $col_value['prd_cat_id']."==".$lastCoupon[0]['cp_cat_id'];
												if ($col_value['prd_cat_id'] != $lastCoupon[0]['cp_cat_id']) {
													$count +=1;
												} else {
													if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
														$coupon_apply = 'only_order';
													}
													if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
														$coupon_apply = 'per_item';
													}
												}
											}
											if ($count == count($_SESSION['shoping_cart'])) {
												$ErrorArray[0] = 'Coupon Code invalid for this collection';
												//$coupon_price = 0;
											}
										}

										//check for product
										if ($lastCoupon[0]['cp_type'] == 'specific_product') {
											$coupon_type = 'specific_product';
											$coupon_product = $lastCoupon[0]['cp_prd_id'];
											$count_product = 0;
											foreach ($_SESSION['shoping_cart'] as $sp_key => $sp_value) {
												if ($sp_value['prd_id'] != $lastCoupon[0]['cp_prd_id']) {
													$count_product +=1;
													//$ErrorArray[0] = 'Coupon code invalid for this product';
												} else {
													if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
														$coupon_apply = 'only_order';
													}
													if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
														$coupon_apply = 'per_item';
													}
												}
											}
											if ($count_product == count($_SESSION['shoping_cart'])) {
												$ErrorArray[0] = 'Coupon code invalid for this product';
												//$coupon_price = 0;
											}
										}
									}
								}
							} 
							else {
								foreach ($_SESSION['shoping_cart'] as $key => $prd_value) {
									$total_Amount += $prd_value['prd_qty'] * $prd_value['prd_price'];
								}


								if ($total_Amount < $lastCoupon[0]['cp_price']) {
									$ErrorArray[] = "The discount amount can't be greater than the subtotal.";
								} else {
									$coupon_code = $lastCoupon[0]['cp_code'];
									$coupon_price = $lastCoupon[0]['cp_price'];

									//check for all order
									if ($lastCoupon[0]['cp_type'] == 'all_order') {
										$coupon_type = 'All order';
										$coupon_apply = '';
									}

									//check for orders over
									if ($lastCoupon[0]['cp_type'] == 'orders_over') {
										// echo $total_Amount."=-==".$lastCoupon[0]['cp_order_price'];

										if ($total_Amount <= $lastCoupon[0]['cp_order_price']) {
											$ErrorArray[] = 'Coupon code only valid for price over '.$lastCoupon[0]['cp_order_price'];
										} else {
											$coupon_type = 'Order Over';
											$coupon_apply = '';
										}
									}

									//check for collection 
									if ($lastCoupon[0]['cp_type'] == 'collection') {
										$count = 0;
										$coupon_type = 'collection';
										$coupon_category = $lastCoupon[0]['cp_cat_id'];
										foreach ($_SESSION['shoping_cart'] as $col_key => $col_value) {
										if ($col_value['prd_cat_id'] != $lastCoupon[0]['cp_cat_id']) {
												$count +=1;
											} else {
												if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
													$coupon_apply = 'only_order';
												}
												if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
													$coupon_apply = 'per_item';
												}
											}
										}
										if ($count == count($_SESSION['shoping_cart'])) {
											$ErrorArray[0] = 'Coupon Code invalid for this collection';
											//$coupon_price = 0;
										}
									}

									//check for product
									if ($lastCoupon[0]['cp_type'] == 'specific_product') {
										$coupon_type = 'specific_product';
										$coupon_product = $lastCoupon[0]['cp_prd_id'];
										$count_product = 0;
										foreach ($_SESSION['shoping_cart'] as $sp_key => $sp_value) {
											if ($sp_value['prd_id'] != $lastCoupon[0]['cp_prd_id']) {
												$count_product +=1;
												//$ErrorArray[0] = 'Coupon code invalid for this product';
											} else {
												if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
													$coupon_apply = 'only_order';
												}
												if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
													$coupon_apply = 'per_item';
												}
											}
										}
										if ($count_product == count($_SESSION['shoping_cart'])) {
											$ErrorArray[0] = 'Coupon code invalid for this product';
											//$coupon_price = 0;
										}
									}
								}
							}
						} else {
							$ErrorArray[] = 'Coupon code expired.';
						}
					} else {
						//if  coupon valid for never expiry

						if ($lastCoupon[0]['no_limit_used'] != 1) {
						
								if ($lastCoupon[0]['cp_used_time'] <= $lastCoupon[0]['cp_used_count']) {
									$ErrorArray[] = 'Invalid coupon code';
								} else {
									foreach ($_SESSION['shoping_cart'] as $key => $prd_value) {
										$total_Amount += $prd_value['prd_qty'] * $prd_value['prd_price'];
									}


									if ($total_Amount < $lastCoupon[0]['cp_price']) {
										$ErrorArray[] = "The discount amount can't be greater than the subtotal.";
									} else {
										$coupon_code = $lastCoupon[0]['cp_code'];
										$coupon_price = $lastCoupon[0]['cp_price'];

										//check for all order
										if ($lastCoupon[0]['cp_type'] == 'all_order') {
											$coupon_type = 'All order';
											$coupon_apply = '';
										}

										//check for orders over
										if ($lastCoupon[0]['cp_type'] == 'orders_over') {
											// echo $total_Amount."=-==".$lastCoupon[0]['cp_order_price'];

											if ($total_Amount <= $lastCoupon[0]['cp_order_price']) {
												$ErrorArray[] = 'Coupon code only valid for price over '.$lastCoupon[0]['cp_order_price'];
											} else {
												$coupon_type = 'Order Over';
												$coupon_apply = '';
											}
										}

										//check for collection 
										if ($lastCoupon[0]['cp_type'] == 'collection') {
											$count = 0;
											$coupon_type = 'collection';
											$coupon_category = $lastCoupon[0]['cp_cat_id'];
											foreach ($_SESSION['shoping_cart'] as $col_key => $col_value) {
	//                                                echo $col_value['prd_cat_id']."==".$lastCoupon[0]['cp_cat_id'];
												if ($col_value['prd_cat_id'] != $lastCoupon[0]['cp_cat_id']) {
													$count +=1;
												} else {
													if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
														$coupon_apply = 'only_order';
													}
													if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
														$coupon_apply = 'per_item';
													}
												}
											}
											if ($count == count($_SESSION['shoping_cart'])) {
												$ErrorArray[0] = 'Coupon Code invalid for this collection';
												//$coupon_price = 0;
											}
										}

										//check for product
										if ($lastCoupon[0]['cp_type'] == 'specific_product') {
											$coupon_type = 'specific_product';
											$coupon_product = $lastCoupon[0]['cp_prd_id'];
											$count_product = 0;
											foreach ($_SESSION['shoping_cart'] as $sp_key => $sp_value) {
												if ($sp_value['prd_id'] != $lastCoupon[0]['cp_prd_id']) {
													$count_product +=1;
													//$ErrorArray[0] = 'Coupon code invalid for this product';
												} else {
													if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
														$coupon_apply = 'only_order';
													}
													if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
														$coupon_apply = 'per_item';
													}
												}
											}
											if ($count_product == count($_SESSION['shoping_cart'])) {
												$ErrorArray[0] = 'Coupon code invalid for this product';
												//$coupon_price = 0;
											}
										}
									}
								}
							} 
							else {
								foreach ($_SESSION['shoping_cart'] as $key => $prd_value) {
									$total_Amount += $prd_value['prd_qty'] * $prd_value['prd_price'];
								}


								if ($total_Amount < $lastCoupon[0]['cp_price']) {
									$ErrorArray[] = "The discount amount can't be greater than the subtotal.";
								} else {
									$coupon_code = $lastCoupon[0]['cp_code'];
									$coupon_price = $lastCoupon[0]['cp_price'];

									//check for all order
									if ($lastCoupon[0]['cp_type'] == 'all_order') {
										$coupon_type = 'All order';
										$coupon_apply = '';
									}

									//check for orders over
									if ($lastCoupon[0]['cp_type'] == 'orders_over') {
										// echo $total_Amount."=-==".$lastCoupon[0]['cp_order_price'];

										if ($total_Amount <= $lastCoupon[0]['cp_order_price']) {
											$ErrorArray[] = 'Coupon code only valid for price over '.$lastCoupon[0]['cp_order_price'];
										} else {
											$coupon_type = 'Order Over';
											$coupon_apply = '';
										}
									}

									//check for collection 
									if ($lastCoupon[0]['cp_type'] == 'collection') {
										$count = 0;
										$coupon_type = 'collection';
										$coupon_category = $lastCoupon[0]['cp_cat_id'];
										foreach ($_SESSION['shoping_cart'] as $col_key => $col_value) {
										if ($col_value['prd_cat_id'] != $lastCoupon[0]['cp_cat_id']) {
												$count +=1;
											} else {
												if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
													$coupon_apply = 'only_order';
												}
												if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
													$coupon_apply = 'per_item';
												}
											}
										}
										if ($count == count($_SESSION['shoping_cart'])) {
											$ErrorArray[0] = 'Coupon Code invalid for this collection';
											//$coupon_price = 0;
										}
									}

									//check for product
									if ($lastCoupon[0]['cp_type'] == 'specific_product') {
										$coupon_type = 'specific_product';
										$coupon_product = $lastCoupon[0]['cp_prd_id'];
										$count_product = 0;
										foreach ($_SESSION['shoping_cart'] as $sp_key => $sp_value) {
											if ($sp_value['prd_id'] != $lastCoupon[0]['cp_prd_id']) {
												$count_product +=1;
												//$ErrorArray[0] = 'Coupon code invalid for this product';
											} else {
												if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
													$coupon_apply = 'only_order';
												}
												if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
													$coupon_apply = 'per_item';
												}
											}
										}
										if ($count_product == count($_SESSION['shoping_cart'])) {
											$ErrorArray[0] = 'Coupon code invalid for this product';
											//$coupon_price = 0;
										}
									}
								}
							}
						

						/*foreach ($_SESSION['shoping_cart'] as $key => $prd_value) {
							$total_Amount += $prd_value['prd_qty'] * $prd_value['prd_price'];
						}
						if ($total_Amount < $lastCoupon[0]['cp_price']) {
							$ErrorArray[] = "The discount amount can't be greater than the subtotal.";
						} else {
							$coupon_code = $lastCoupon[0]['cp_code'];
							$coupon_price = $lastCoupon[0]['cp_price'];
							//check for all order
							if ($lastCoupon[0]['cp_type'] == 'all_order') {
								$coupon_type = 'All order';
								$coupon_apply = '';
							}
							//check for orders over
							if ($lastCoupon[0]['cp_type'] == 'orders_over') {
								// echo $total_Amount."=-==".$lastCoupon[0]['cp_order_price'];

								if ($total_Amount <= $lastCoupon[0]['cp_order_price']) {
									$ErrorArray[] = 'Coupon code only valid for price over '.$lastCoupon[0]['cp_order_price'];
								} else {
									$coupon_type = 'Order Over';
									$coupon_apply = '';
								}
							}

							//check for collection 
							if ($lastCoupon[0]['cp_type'] == 'collection') {
								$count = 0;
								$coupon_type = 'collection';
								$coupon_category = $lastCoupon[0]['cp_cat_id'];
								foreach ($_SESSION['shoping_cart'] as $col_key => $col_value) {
	//                                                echo $col_value['prd_cat_id']."==".$lastCoupon[0]['cp_cat_id'];
									if ($col_value['prd_cat_id'] != $lastCoupon[0]['cp_cat_id']) {
										$count +=1;
									} else {
										if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
											$coupon_apply = 'only_order';
										}
										if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
											$coupon_apply = 'per_item';
										}
									}
								}
								if ($count == count($_SESSION['shoping_cart'])) {
									$ErrorArray[0] = 'Coupon Code invalid for this collection';
									//$coupon_price = 0;
								}
							}

							//check for product
							if ($lastCoupon[0]['cp_type'] == 'specific_product') {
								$coupon_type = 'specific_product';
								$coupon_product = $lastCoupon[0]['cp_prd_id'];
								$count_product = 0;
								foreach ($_SESSION['shoping_cart'] as $sp_key => $sp_value) {
									if ($sp_value['prd_id'] != $lastCoupon[0]['cp_prd_id']) {
										$count_product +=1;
										//$ErrorArray[0] = 'Coupon code invalid for this product';
									} else {
										if ($lastCoupon[0]['cp_apply_discount'] == 'only_order') {
											$coupon_apply = 'only_order';
										}
										if ($lastCoupon[0]['cp_apply_discount'] == 'per_item') {
											$coupon_apply = 'per_item';
										}
									}
								}
								if ($count_product == count($_SESSION['shoping_cart'])) {
									$ErrorArray[0] = 'Coupon code invalid for this product';
									//$coupon_price = 0;
								}
							}
						}*/
					}
				}

				if ($coupon_code != '' && count($lastCoupon) == 0) {
					$ErrorArray[] = 'Invalid coupon code.';
				}
				
				

				if (count($ErrorArray) > 0) {
					$_SESSION['coupon_detail']['coupon_staus'] = 'invalid';
					$coupon_price = '';
					$coupon_type = '';
					$coupon_apply = '';
					$coupon_category = '';
					$coupon_product ='';
				} else {
					$_SESSION['coupon_detail']['coupon_staus'] = 'valid';
				}
				$_SESSION['coupon_detail']['coupon_code'] = $coupon_code;
				$_SESSION['coupon_detail']['coupon_price'] = $coupon_price;
				$_SESSION['coupon_detail']['coupon_type'] = $coupon_type;
				$_SESSION['coupon_detail']['coupon_applied'] = $coupon_apply;
				$_SESSION['coupon_detail']['coupon_category'] = $coupon_category;
				$_SESSION['coupon_detail']['coupon_product'] = $coupon_product;
			}
        }



        if (isset($_POST['quantity'])) {

            function IsEmpty($value = '') {
                if (trim($value) == '') {
                    return true;
                }
                return false;
            }

            function isvalidQuantity($n) {
                if (!preg_match("/^[0-9]+$/", $n)) {
                    return false;
                }
                if ($n <= 0) {
                    return false;
                }
                return true;
            }

            $errorMessage = Array();
            $postedData = $_POST;


            if (IsEmpty($postedData['quantity'])) {
                $errorMessage = "Quantity cannot be blank";
            } else {
                if (!isvalidQuantity($postedData['quantity'])) {
                    $errorMessage = "Quantity should be a number greater than zero";
                }
            }


            if (count($errorMessage) > 0) {
                $this->view->quantity_numb = $postedData['quantity'];
                $this->view->ErrorMessage = $errorMessage;
            } else {


                $prd_id = $_POST['product_id'];
                $productArray = $sql->fetch("tbl_product", array("prd_id" => $prd_id));
                /* if(in_array($prd_id, $productArray)){
                  $this->view->ErrorMessage = "Product already added.";
                  } */

                $cart = $_SESSION['shoping_cart'];
                $cnt = 0;
                $product_qty = $postedData['quantity'];

                /* if(count($_SESSION['shoping_cart']) > 0){
                  $coupon_price = $_SESSION['shoping_cart'][0]['coupon_price'];
                  $coupon_code = $_SESSION['shoping_cart'][0]['coupon_code'];
                  } */
                if (isset($_POST['remove_product'])) {
                    $prd_id = $_POST['product_id'];
                    $productArray = $sql->fetch("tbl_product", array("prd_id" => $prd_id));
                    $pid = "";
                    $cart = $_SESSION['shoping_cart'];
                    foreach ($cart as $subKey => $subArray) {
                        if ($subArray['prd_id'] == $_POST['product_id']) {
                            $pid = $subArray['prd_id'];
                            unset($cart[$subKey]);
                        }
                    }
                    $countArray = count($cart);
                    $_SESSION['shoping_cart'] = $cart;
                    //$this->view->successMessage = "Product add to cart.";
                    if ($pid != '') {
                        $_SESSION['view_message'] = "Product Removed from your cart.";
                    } else {
                        unset($_SESSION['view_message']);
                    }
                }


                if (count($cart) > 0) {

                    foreach ($cart as $subKey => $subArray) {
                        if ($subArray['prd_id'] == $productArray['prd_id']) {
                            //$this->view->quantity_numb = $product_qty;
                            $cart[$subKey]['prd_qty'] = $product_qty; //$cart[$subKey]['prd_qty'] + $product_qty;
                            $cnt++;
                        }
                    }

                    $_SESSION['shoping_cart'] = $cart;
                    foreach ($_SESSION['shoping_cart'] as $key => $prd_value) {
                        $total_Amount += $prd_value['prd_qty'] * $prd_value['prd_price'];
                    }
                    if ($total_Amount < $_SESSION['coupon_detail']['coupon_price']) {
                        unset($_SESSION['coupon_detail']);
                    }

                    header('Location: ' . URL . 'cart');
                }
            }
        }

        $Discount_price = 0;
        $Discount_code = '';
        $total_Amount1 = '';
        if (isset($_SESSION['shoping_cart']) && count($_SESSION['shoping_cart']) > 0) {
            foreach ($_SESSION['shoping_cart'] as $key => $value) {
                $total_Amount1 += $value['prd_qty'] * $value['prd_price'];
            }
        }

        if (isset($_SESSION['coupon_detail'])) {
            $Discount_price = $_SESSION['coupon_detail']['coupon_price'];
            $Discount_code = $_SESSION['coupon_detail']['coupon_code'];
        }
        $Final_amount_with_discount = $total_Amount1 - $Discount_price;

        /* if($Final_amount_with_discount == 0){
          $_SESSION['coupon_detail']['coupon_staus'] = 'invalid';
          } */





        if (array_key_exists('coupon_code', $_POST)) {

            $coupon_code = $_POST['coupon_code'];
            $lastcouponquery1 = "select * from tbl_coupon where cp_code ='" . $coupon_code . "' and cp_status = 1 and cp_expiry_date >= '" . date('Y-m-d') . "' ";
            $lastCoupon1 = $sql->SimpleQuery($lastcouponquery1);
            if (count($lastCoupon1) == 0) {
                $invalid_coupon_code = 'yes';
            }
        }

        $this->view->errorMessageArray = $ErrorArray;
        $this->view->invalid_coupon = $invalid_coupon_code;
        $this->view->Final_amount_with_discount = $Final_amount_with_discount;
        $this->view->coupon_price = $coupon_price;
        $this->view->coupon_code = $coupon_code;


        $this->view->render('cart');
    }

}
